package hy.planegame.sprite

import android.graphics.Canvas
import hy.planegame.utils.*

/**
 * Created time : 2017/9/1 11:24.
 * @author HY
 */
class Enemy : Sprite<Enemy>(), Comparable<Enemy> {
    override fun compareTo(other: Enemy): Int = a * b - other.a * other.b

    private val a = random.nextInt(20)
    private val b = random.nextInt(20)

    private var health = if (a < b) 300 else 500

    private val bitmap= if (a < b) small else middle

    private val width = bitmap.width
    private val height = bitmap.height
    private val x: Int
    private var y: Int = -height
    private var isDestroy = false

    private val boom = Boom()

    private var count = 0

    init {
        x = random.nextInt(screenWidth - width)

        boom.stop {
            _onDestroy?.invoke()
        }
    }

    override fun draw(canvas: Canvas?) {
        if (!isDestroy) {
            canvas ?: return

            canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), paint)
        } else {
            boom.draw(canvas)
        }
    }

    override fun logic() {
        if (!isDestroy) {
            if (y <= screenHeight) {
                y += 15

            } else {
                destroy()
            }

            if (count % 50 == 0) {
                val bullet = EnemyBullet(x + width / 2, y + height)
                bullet.onDestroy {
                    _onBulletDestroy?.invoke(bullet)
                }

                _onAdd?.invoke(bullet)
            }
            count++
        } else {
            boom.logic()
        }
    }

    private var _onBulletDestroy: ((enemyBullet: EnemyBullet) -> Unit)? = null

    fun onBulletDestroy(callback: (enemyBullet: EnemyBullet) -> Unit) {
        _onBulletDestroy = callback
    }

    private var _onAdd: ((enemyBullet: EnemyBullet) -> Unit)? = null
    fun addBullet(callback: (enemyBullet: EnemyBullet) -> Unit) {
        _onAdd = callback
    }

    private var _onDestroy: (() -> Unit)? = null

    fun onDestroy(callback: () -> Unit) {
        _onDestroy = callback
    }

    fun isCollision(bullet: Bullet): Boolean {
        if (isDestroy) return false

        val left = bullet.centerX - bullet.width / 2
        val right = left + bullet.width
        val top = bullet.y
        val bottom = top + bullet.height

        if (((left < x + width && left > x) || (right > x && right < x + width)) && ((bottom > y && bottom < y + height) || (top < y + height && top > y))) {

            return true
        }
        return false
    }

    override fun destroy() {
        isDestroy = true
        boom.start(x + width / 2, y + height / 2)
    }
}